<?php
use \Phalcon\Mvc\View;
use \Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Email as EmailValidator;

class AccountController extends \Phalcon\Mvc\Controller
{

    public function indexAction()
    {
    	// echo $this->crypt->decryptBase64('bSMPbvQ/hAA5AlZXYEadUA8EsmItiz90NdkZjhbNAP4dty0arUo5hXyVcRjqia1HaRoDONUMqH7cCmO3vzjeKw==');
    }

    public function registerAction()
    {

    	$inside_department = OdpDepartment::find("is_inside_school = 1");
    	// var_dump($inside_departmnt->toArray());exit();
    	$byside_department = OdpDepartment::find("is_inside_school = 0");
    	
    	//记录个session供captcha简单验证
    	$this->session->set('captcha','work');

    	$this->assets
			->addCss('public/css/bootstrap/3.2.0/css/bootstrap.min.css')
			->addCss('public/css/ace/ace.min.css')
			->addCss('public/css/ace/ace-rtl.min.css')
    		->addCss("public/css/reg/register.css");

		$this->assets
			->addJs('public/js/jquery/jquery-2.1.1.min.js')
			->addJs('public/js/jquery/jquery.easing.min.js')
			->addJs('public/js/bootstrap/3.2.0/bootstrap.min.js')
			->addJs('public/js/angular/1.2.19/angular.min.js')
			->addJs('public/js/angular-strap/angular-strap.min.js')
			->addJs('public/js/angular-strap/angular-strap.tpl.min.js')
			->addJs('public/js/angular-strap/modules/popover.js')
			->addJs('public/angular/controller/registerController.js')
			->addJs('public/js/register.js');
    	$this->view->setVar("title","用户注册");
    	$this->view->setVar("inside_department",$inside_department);
    	$this->view->setVar("byside_department",$byside_department);
		$this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
		$this->view->render('account','register');
    }

    //提供手机验证码
    public function captchaAction()
    {

    	if($this->session->get('captcha')!='work')
    	{
    		die('Bad Request!');
    	}

    	//客户端已验证，为了安全这里仍然需要再验证
    	$phoneNumber = $this->request->get('phoneNumber');
    	$data = ['phoneNumber'=>$phoneNumber];
    	$validation = new \Phalcon\Validation();

    	$validation->add('phoneNumber', new RegexValidator(array(
			'pattern' => '/^0?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/',
			'message' => 'Wrong Phone Number'
		)));


		if ( $messages = $validation->validate($data) ) {

			if(is_null($messages[0]))
			{
				if($this->memcached->exists($phoneNumber))
				{
					$captcha = $this->memcached->get($phoneNumber);
				}else{
					//检查号码是否已注册

					$search_mphone = OdpTeacher::findFirst(array("mobile_phone = :mphone:","bind"=>array("mphone"=>$phoneNumber)));
					if($search_mphone)
					{
						if($search_mphone->teacher_id>0)
						{
							$msg = array(
								'code' => '-1',
								'message' => "手机号已被注册！"
								);
							die(json_encode($msg));
						}
					}

					//设置为NULL,否则memcached会将每个key存储，容量迅速增大
					$this->memcached->setTrackingKey('');

					//验证通过,生成6位数字验证码，验证码有生命期
					$captcha = Phalcon\Text::random(Phalcon\Text::RANDOM_NUMERIC,6);
					// $captcha = 666666;
					$this->memcached->save($phoneNumber,$captcha,300);	
				}

				//发送短信
				// $result = $this->notify->sendCaptchaSMS($phoneNumber,$captcha);
				$result=200;
				$message = ($result)?'已发送验证码':'发送失败';
				$msg = array(
						'code' => $result,
						'message' => $message
					);
				echo json_encode($msg);
			}else{
				$msg = array(
						'code' => $messages[0]->getCode(),
						'message' => $messages[0]->getMessage()
					);

				echo json_encode($msg);
			}


		}

    }

    public function addUserAction()
    {
    	//确保来自注册页面
    	if($this->session->get('captcha')!='work')
    	{
    		die('Bad Request!');
    	}
    	$msg = array();

    	$data = $this->request->getJsonRawBody();

    	//写库之前进行数据检查

    	if($data)
    	{
    		/**************************************
    		*
    		*检查手机号码
    		*
    		****************************************/
    		$teacher = new OdpTeacher();
    		$phoneNumber = $data->user->phoneNumber;

    		// echo $phoneNumber;exit();
	    	$validPhoneNumber = ['phoneNumber'=>$phoneNumber];
	    	$validation = new \Phalcon\Validation();

	    	$validation->add('phoneNumber', new RegexValidator(array(
				'pattern' => '/^0?(13[0-9]|15[0-9]|17[678]|18[0-9]|14[57])[0-9]{8}$/',
				'message' => '手机号码不正确'
			)));
			if ( $messages = $validation->validate($validPhoneNumber) ) {
				if(is_null($messages[0])){
					//号码正确，开始检查captcha
					if($captcha=$data->user->captcha){

						$mem_captcha=$this->memcached->get($phoneNumber);
						if($captcha!=$mem_captcha){
							$msg = array('code'=>0,'message'=>"验证码过期或不正确，请重新获取");
							die(json_encode($msg));
						}

					}else{
						$msg = array('code'=>0,'message'=>"验证码不能为空");
						die(json_encode($msg));
					}

				}else{

					$msg = array(
						'code' => $messages[0]->getCode(),
						'message' => $messages[0]->getMessage()
					);
					die(json_encode($msg));
				}
			}//validate phoneNumber--->

			/**************************************
    		*
    		*验证email部分
    		*
    		****************************************/

			$email = $data->user->email;
			// $email = "ffsf3.ewrfe.sdfsdg.sdgs@g";
			$validateEmail = ['email'=>$email];
			$validation_email = new \Phalcon\Validation();
			$validation_email->add('email',new EmailValidator(array(
				'message'=>"Email格式不合法"
			)));
			if($messagesEmail = $validation_email->validate($validateEmail))
			{
				if(!is_null($messagesEmail[0])){
					$msg = array(
						'code' => $messagesEmail[0]->getCode(),
						'message' => $messagesEmail[0]->getMessage()
					);
					die(json_encode($msg));
				}
			}

			
			//email与手机号码不重合，进行验证
			$search_email = OdpTeacher::findFirst(array(" email = :em: ","bind"=>array("em"=>$email)));
			if($search_email)
			{
				if($search_email->teacher_id>0)
				{
					$msg = array(
						'code' => '0',
						'message' => "Email已被注册，忘记密码请重置！"
					);
					die(json_encode($msg));
				}
			}

			// $encrypt_phoneNumber = $this->crypt->encryptBase64($phoneNumber);
			$search_mphone = OdpTeacher::findFirst(array("mobile_phone = :mphone:","bind"=>array("mphone"=>$phoneNumber)));
			if($search_mphone)
			{
				if($search_mphone->teacher_id>0)
				{
					$msg = array(
						'code' => '0',
						'message' => "手机号已被注册！"
					);
					die(json_encode($msg));
				}
			}
    	}else{
    		//if data null 如果没有数据上传
    		$msg=array('code'=>'0','message'=>"Miss data collection!!");
    		die(json_encode($msg));
    	}

    	//准备数据
    	$sideschool =array('byside'=>0,'inside'=>1,'out'=>2);
    	$is_inside_school = $sideschool[$data->user->isInsideSchool];

		$email_verificaion_code = Phalcon\Text::random(Phalcon\Text::RANDOM_ALNUM,24);
		$officePhone =(isset($data->user->officePhone))?$data->user->officePhone:NUll;
		$duty = (isset($data->user->duty))?$data->user->duty:NUll;
		// var_dump($encrypt_phoneNumber);
    	//写入数据
		
    	$teacher->assign(array( 
    		'school_id' => '13967',
            'department_id' => $data->user->department, 
            'teacher_name' => $data->user->tname, 
            'professional_title' => $data->user->ptitle, 
            'teacher_pwd' => md5($data->user->passwd), 
            'teacher_sex' => $data->user->sex, 
            'is_inside_school' => $is_inside_school,
            'is_working' => 1,
            'email' => $email, 
            'office_phone' => $officePhone, 
            'mobile_phone' => $phoneNumber, 
            'email_verificaion_code' => $email_verificaion_code, 
            'is_email_verified' => 0, 
            'register_time' => time(),
            'last_login_time' => 0,
            'is_imported' => 0,
            'duty'=>$duty
    	));
    	// echo $teacher->getDirtyState();
		if($teacher->save()==false){

			$msg = array(
				'code' => '0',
				'message' => "发生异常错误，请联系系统管理员"
			);
		}else{

			$result = $this->notify->sendVerificationEmail($email,$data->user->tname,$email_verificaion_code);
			// var_dump($result);
			if($result)
			{
				$msg = array(
					'code' => '1',
					'message' => "注册成功,请查看邮件验证邮箱！"
				);
			}else{
				$msg = array(
					'code' => '1',
					'message' => "注册成功,激活邮件发送失败！！"
				);	
			}

		}
		die(json_encode($msg));

    	// var_dump($data->user);
    	// $header = $this->request->getHeader('X-XSRF-TOKEN');
    	// var_dump($header);
    	// $this->response->setContentType('application/json', 'UTF-8');
    	// $this->response->setContent(json_encode($data));
    	// $this->response->send();
    	

    }

    public function captchaImgAction()
    {
    	if($this->session->get("CAPTCHA_IMG")!="enabled")
    		die("Bad Request");
    	
    	$this->captcha->showImg(150,30,5);
    	$code = $this->captcha->getCaptcha();

    	$this->session->set("captcha_code",$code);

    }

    public function resetPasswordAction()
    {
		if($this->session->get("CAPTCHA_IMG")!="enabled")
    		die("Bad Request");
    	$data = $this->request->getJsonRawBody();
    	$msg=array();
    	if($data)
    	{
    		if(isset($data->teacher->captcha))
    			$captcha = $data->teacher->captcha;
    		else
    			die(json_encode(array('code'=>'0','message'=>"验证码丢失!!")));

    		if(strtolower($captcha)==strtolower($this->session->get('captcha_code')))
    		{
    			//验证码正确，查询手机号码是否存在，并所有人为该姓名的教师
    			$teacher = OdpTeacher::findFirst(array("mobile_phone = :mphone:","bind"=>array("mphone"=>$data->teacher->phoneNumber)));
    			if($teacher)
    			{
    				if($teacher->teacher_name==$data->teacher->tname)
    				{
    					//重置密码
    					$newPwd = Phalcon\Text::random(Phalcon\Text::RANDOM_ALNUM,8);
    					$teacher->teacher_pwd = md5($newPwd);
    					if($teacher->save())
    					{
    						$result = $this->notify->sendResetPwdSMS($data->teacher->phoneNumber,$newPwd);
    						// $result=1;
    						if($result){
    							die(json_encode(array('code'=>'1','message'=>"恭喜！密码重置成功！请查看手机短消息！")));
    						}
    					}

    				}else{
    					die(json_encode(array('code'=>'0','message'=>"注意！手机号码与姓名不匹配!!")));
    				}
    			}else{
    				die(json_encode(array('code'=>'0','message'=>"注意！此手机号码不存在!!")));
    			}


    		}else{
    			die(json_encode(array('code'=>'0','message'=>"验证码错误，请重新输入!!")));
    		}

    	}else{
			//if data null 如果没有数据上传
    		$msg=array('code'=>'0','message'=>"Miss data collection!!");
    		die(json_encode($msg));
    	}
    }
    
}

